package com.yunhe.option.thread;

import com.alibaba.fastjson.JSON;
import com.yunhe.common.util.RedisClient;
import com.yunhe.option.domain.base.Enum;
import com.yunhe.option.domain.base.Item;
import com.yunhe.option.service.base.EnumService;
import com.yunhe.option.service.base.ItemService;
import com.yunhe.option.utils.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yunhe.common.util.CollectionUtil;

import java.util.List;
import java.util.Map;

/**
 * @ClassName DoCacheJob
 * @Description TODO
 * @Author HeTao
 * @Date 2021/3/17 9:34
 * @Version 1.0
 **/
public class DoCacheJob implements Runnable{

    private static Logger logger = LoggerFactory.getLogger(DoCacheJob.class);

    private Map<Integer,String> map ;
    private int j;

    public DoCacheJob(Map<Integer, String> map,int j) {
        this.map = map;
        this.j = j;
    }

    @Override
    public void run() {
        //执行数据的写入操作
        String dataOffects = map.get(j);
        String[] splits = dataOffects.split(":");
        int start = Integer.valueOf(splits[0]);
        int end = Integer.valueOf(splits[1]);
        //执行数据分片写入缓存
        ItemService itemService = SpringContextUtil.getBean("itemServiceImpl");
        RedisClient redisUtil = SpringContextUtil.getBean("redisClient");
        EnumService enumService = SpringContextUtil.getBean("enumServiceImpl");
        List<Enum> enumList = (List<Enum>)enumService.findAll();
        if(!CollectionUtil.isEmpty(enumList)){
            if(enumList.size() <= end){
                end = enumList.size();
            }
            List<Enum> enums1 = enumList.subList(start - 1, end);
            logger.info("线程"+j+"处理数据"+enums1.size());
            if(!CollectionUtil.isEmpty(enums1)){
                for (Enum anEnum : enums1) {
                    List<Item> items = (List<Item>) itemService.getItemByItemCodeAndEnumName(anEnum.getName());
                    if(!CollectionUtil.isEmpty(items)){
                        redisUtil.set("ENUM_ITEM:"+anEnum.getName(), JSON.toJSONString(items));
                    }
                }
            }
        }

    }
}